<template>
	<view class="uni-container">
		<uni-forms ref="form" v-model="formData" validateTrigger="bind">
			<uni-forms-item name="id" label="店铺编号">
				<uni-easyinput placeholder="创建自动生成" type="number" disabled="disabled" v-model="formData.id" />
			</uni-forms-item>
			<uni-forms-item name="name" label="店铺名称">
				<uni-easyinput placeholder="" v-model="formData.name" />
			</uni-forms-item>
			<uni-forms-item name="state" label="是否启用">
				<switch @change="binddata('state', $event.detail.value)" :checked="formData.state" />
			</uni-forms-item>
			<uni-forms-item name="notice" label="店铺公告">
				<uni-easyinput placeholder="" v-model="formData.notice" />
			</uni-forms-item>
			<uni-forms-item name="addressObject" label="地址">
				<cloud-map v-model="formData.addressObject"></cloud-map>
			</uni-forms-item>
			<uni-forms-item name="addressName" label="地址简称">
				<uni-easyinput placeholder="店铺地址简称，例如：鸿升大厦" v-model="formData.addressName" />
			</uni-forms-item>
			<uni-forms-item name="currency" label="币种">
				<uni-data-checkbox v-model="formData.currency" :localdata="formOptions.currency_localdata" />
			</uni-forms-item>
			<uni-forms-item name="phone" label="联系电话">
				<uni-easyinput placeholder="" v-model="formData.phone" />
			</uni-forms-item>
			<uni-forms-item name="deliveryTypes" label="配送方式">
				<uni-data-checkbox :multiple="true" v-model="formData.deliveryTypes"
					:localdata="formOptions.deliveryTypes_localdata" />
			</uni-forms-item>
			<uni-forms-item name="serviceTime" label="服务时间">
				<uni-easyinput placeholder="" v-model="formData.serviceTime" />
			</uni-forms-item>
			<uni-forms-item name="src" label="店铺logo">
				<cloud-image v-model="formData.src"></cloud-image>
			</uni-forms-item>
			<uni-forms-item name="banner" label="banner">
				<cloud-image v-model="formData.banner" imageClass="banner"></cloud-image>
			</uni-forms-item>
			<!-- 			<uni-forms-item name="goodsCommentTags" label="商品评论标签">
				<uni-data-checkbox :multiple="true" v-model="formData.goodsCommentTags" />
			</uni-forms-item>
			<uni-forms-item name="searchGoodsKeywords" label="商品搜索词">
				<uni-data-checkbox :multiple="true" v-model="formData.searchGoodsKeywords" />
			</uni-forms-item> -->
			<view class="uni-button-group">
				<button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
				<navigator open-type="navigateBack" style="margin-left: 15px;">
					<button class="uni-button" style="width: 100px;">返回</button>
				</navigator>
			</view>
		</uni-forms>
	</view>
</template>

<script>
	import validator from '@/js_sdk/validator/cloud_shops.js';

	const db = uniCloud.database();
	const dbCmd = db.command;
	const dbCollectionName = 'cloud_shops';

	function getValidator(fields) {
		let reuslt = {}
		for (let key in validator) {
			if (fields.includes(key)) {
				reuslt[key] = validator[key]
			}
		}
		return reuslt
	}

	export default {
		data() {
			return {
				formData: {
					"address": "",
					"addressName": "",
					"banner": null,
					"currency": "cny",
					"dayStatisticsLog": "",
					"deliverySupportType": 3,
					"deliveryTypes": [
						"deliveryHome",
						"selfRaising"
					],
					"hasManjian": 1,
					"id": 0,
					"isPrint": false,
					"lastPayTimeMinute": 30,
					"latitude": 29.139011,
					"longitude": 107.008728,
					"manjians": [],
					"monthSale": 0,
					"name": "",
					"notice": "",
					"online": true,
					"perCapita": 30,
					"phone": "",
					"printers": [],
					"score": 4.8,
					"searchGoodsKeywords": [],
					"selfRaising": {
						"enable": false
					},
					"serviceTime": "早上7点到晚上10点",
					"src": null,
					"state": true,
					"stationId": 0,
					"uid": "",
					"video": false,
					addressObject: {}
				},
				formOptions: {
					"currency_localdata": [{
							"text": "￥人民币",
							"value": "cny"
						},
						{
							"text": "A$澳币",
							"value": "aud"
						},
						{
							"text": "美金",
							"value": "usd"
						},
						{
							"text": "C$加拿大元",
							"value": "cad"
						},
						{
							"text": "€欧元",
							"value": "eur"
						},
						{
							"text": "£英镑",
							"value": "gbp"
						},
						{
							"text": "NZ$新西兰元",
							"value": "nzd"
						},
						{
							"text": "JP¥日元",
							"value": "jpy"
						},
						{
							"text": "₩韩元",
							"value": "krw"
						}
					],
					"deliveryTypes_localdata": [{
							"text": "配送到家",
							"value": "deliveryHome"
						},
						{
							"text": "到店/自提点自提",
							"value": "selfRaising"
						}
					]
				},
				rules: {
					...getValidator(["address", "addressName", "banner", "currency", "delivery", "deliveryTypes",
						"exchangeRate",
						"goodsCommentTags", "id", "isPrint", "latitude", "longitude", "monthSale", "name", "notice",
						"online", "phone",
						"score", "searchGoodsKeywords", "selfRaisingPoint", "serviceTime", "src", "uid", "state"
					])
				}
			}
		},
		onLoad(e) {
			const id = e.id
			this.formDataId = id
			this.getDetail(id)
		},
		onReady() {
			this.$refs.form.setRules(this.rules)
		},
		methods: {
			/**
			 * 触发表单提交
			 */
			submit() {
				uni.showLoading({
					mask: true
				})
				this.$refs.form.submit().then((res) => {
					res.address = this.formData.addressObject.name;
					res.latitude = this.formData.addressObject.latitude;
					res.longitude = this.formData.addressObject.longitude;
					res.lnglat = this.formData.addressObject.location;
					//合并字段
					/* res = Object.assign(this.formData, {
						...res
					}); */
					console.log(res)
					console.log(this.formData)
					this.submitForm(res)
				}).catch((errors) => {
					uni.hideLoading()
				})
			},

			submitForm(value) {
				// 使用 unicloud-db 提交数据
				db.collection(dbCollectionName).doc(this.formDataId).update(value).then((res) => {
					uni.showToast({
						title: '修改成功'
					})
					this.getOpenerEventChannel().emit('refreshData')
					setTimeout(() => uni.navigateBack(), 500)
				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				}).finally(() => {
					uni.hideLoading()
				})
			},

			/**
			 * 获取表单数据
			 * @param {Object} id
			 */
			getDetail(id) {
				uni.showLoading({
					mask: true
				})
				db.collection(dbCollectionName).doc(id).field(
					'address,addressName,banner,currency,delivery,deliveryTypes,exchangeRate,goodsCommentTags,id,isPrint,latitude,longitude,lnglat,monthSale,name,notice,online,phone,score,searchGoodsKeywords,selfRaising,serviceTime,src,selfRaisingPoint,state,video,dayStatisticsLog,deliverySupportType,lastPayTimeMinute,hasManjian,stationId,perCapita,addressObject,manjians,printers,categories,operator'
				).get({
					getOne: true
				}).then(({
					result
				}) => {
					const data = result.data
					if (data) {
						this.formData = Object.assign(this.formData, {
							...data
						})
						delete this.formData._id;
						console.log(this.formData)
						if (!this.formData.addressObject) {
							this.formData.addressObject = {
								name: data.address,
								latitude: data.latitude,
								longitude: data.longitude,
								location: new db.Geo.Point(data.longitude, data.latitude)
							}
						}
					}
				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				}).finally(() => {
					uni.hideLoading()
				})
			}
		}
	}
</script>
